import React, {useState} from 'react';
import {Button, Card, Descriptions, message, Modal, Space, Typography} from 'antd';
import {getCurrentUser} from '../api/divide/user/sdk.gen';

const {Title, Text} = Typography;

interface TestResult {
    type: 'user_info';
    success: boolean;
    message: string;
    data?: any;
    error?: string;
}

const TestCookieAuth: React.FC = () => {
    const [loading, setLoading] = useState(false);
    const [modalVisible, setModalVisible] = useState(false);
    const [testResult, setTestResult] = useState<TestResult | null>(null);

    // 测试获取当前用户信息（需要cookie认证）
    const testAuthEndpoint = async () => {
        setLoading(true);
        try {
            console.log('测试认证端点...');
            const response = await getCurrentUser();
            console.log('API响应:', response);

            if (response.data?.data) {
                const userData = response.data.data;
                setTestResult({
                    type: 'user_info',
                    success: true,
                    data: userData,
                    message: '认证成功！用户信息已获取'
                });
                message.success('认证成功！用户信息已获取');
            } else {
                setTestResult({
                    type: 'user_info',
                    success: false,
                    message: '未获取到用户信息，可能未登录'
                });
                message.error('未获取到用户信息，可能未登录');
            }
            setModalVisible(true);
        } catch (error) {
            console.error('API调用失败:', error);
            setTestResult({
                type: 'user_info',
                success: false,
                message: 'API调用失败，请检查网络连接',
                error: undefined
            });
            message.error('API调用失败，请检查网络连接');
        } finally {
            setLoading(false);
        }
    };


// 页面加载时尝试获取用户信息
//     useEffect(() => {
//         testAuthEndpoint();
//     }, []);

    return (
        <div style={{padding: '24px', maxWidth: '800px', margin: '0 auto'}}>
            <Title level={2}>Cookie认证测试页面</Title>

            <Space direction="vertical" size="large" style={{width: '100%'}}>
                <Card title="认证状态测试">
                    <Space direction="vertical" size="middle" style={{width: '100%'}}>
                        <Button
                            type="primary"
                            onClick={testAuthEndpoint}
                            loading={loading}
                        >
                            测试认证状态
                        </Button>


                    </Space>
                </Card>

                <Card title="使用说明">
                    <Space direction="vertical">
                        <Text>1. 请先登录系统</Text>
                        <Text>2. 登录后，浏览器会自动设置认证cookie</Text>
                        <Text>3. 点击"测试认证状态"验证cookie是否生效</Text>

                    </Space>
                </Card>

                <Card title="调试信息">
                    <Space direction="vertical" size="small">
                        <Text>API方法: getCurrentUser() / checkLogin()</Text>
                        <Text>认证方式: Cookie认证</Text>
                        <Text>跨域配置: 已启用withCredentials</Text>
                    </Space>
                </Card>
            </Space>

            <Modal
                title="测试结果"
                open={modalVisible}
                onCancel={() => setModalVisible(false)}
                footer={[
                    <Button key="close" onClick={() => setModalVisible(false)}>
                        关闭
                    </Button>
                ]}
            >
                {testResult && (
                    <div>
                        <p style={{color: testResult.success ? 'green' : 'red'}}>
                            {testResult.message}
                        </p>
                        {testResult.type === 'user_info' && testResult.success && testResult.data && (
                            <Descriptions column={1} size="small" bordered>
                                <Descriptions.Item label="用户ID">{testResult.data.id}</Descriptions.Item>
                                <Descriptions.Item label="用户名">{testResult.data.username}</Descriptions.Item>
                                <Descriptions.Item label="邮箱">{testResult.data.email}</Descriptions.Item>
                                {/*<Descriptions.Item label="角色">{testResult.data.role}</Descriptions.Item>*/}
                                <Descriptions.Item label="状态">
                                    {testResult.data.status}
                                </Descriptions.Item>
                            </Descriptions>
                        )}

                        {testResult.error && (
                            <div style={{marginTop: 16}}>
                                <p style={{color: 'red'}}>错误详情:</p>
                                <pre style={{fontSize: 12, color: '#666'}}>
                  {JSON.stringify(testResult.error, null, 2)}
                </pre>
                            </div>
                        )}
                    </div>
                )}
            </Modal>
        </div>
    );
};

export default TestCookieAuth;